# -*- coding: utf-8 -*-
import cfg, core.core as core, re, time, thread
from core.core import IRCError, BadBotDescriptor, Servers, escape_for_regexp
from core.optimizers import File, GetParams, Logs

newpages = File("newpages")
class Bot(core.SimpleIRCBot):
	def __init__(self, bot, client):
		core.SimpleIRCBot.__init__(self, bot, client)
		self.newartchan = cfg.newartchan
		self.triggers = escape_for_regexp(cfg.triggers)

	def on_welcome(self, evt):
		print "%s bot.py ON_WELCOME" % time.strftime("[%H:%M:%S]")
		self.bots = Bots
		self.is_connected = True
		Bots.run()

	def on_privmsg(self, evt):
		print "%s bot.py ON_PRIVMSG" % time.strftime("[%H:%M:%S]")
		if self.label[1] > 0:
			self.ctrl_msg(evt.msg)

	def on_pubmsg(self, evt):
		return True #event cancelled
		m = re.search("\x034 *([!NM]+)*\x0310", evt.msg)
		if self.label[1] > 0 and evt.target != "#ca.wikipedia" \
		and "N" in m.group(1) if m and m.group(1) else False:
			self.ctrl_msg(evt.msg)
			newpages.put(
				"[{time}] {channel} {message}" . format(
					time = time.strftime("%c"),
					channel = evt.target,
					message = "%r" % evt.msg
				)
			)

def read_logs():
	l = Logs()
	clean_inactive(l)
	time.sleep(10)

def main():
	global Bots
	try:
		FrBot = Bot(cfg.frBot, cfg.client)
		WmBot = Bot(cfg.wmBot, cfg.client)
		ClonBot = Bot(cfg.frBot2, cfg.client)
		Bots = Servers(FrBot, WmBot, ClonBot) if args.get("clon") else Servers(FrBot, WmBot)
		FrBot.start()
	except KeyboardInterrupt:
		for bot in Bots.args:
			if bot.is_connected:
				bot.quit("O_O I hate Ctrl-C!!! >:D")
		FrBot.logs.IPs.save()
		FrBot.logs.users.save()
	except IRCError:
		for bot in Bots.args:
			bot.reconnect()
	except BadBotDescriptor:
		pass

if __name__ == "__main__":
	Bots = None
	args = GetParams()
	if args.get("r"):
		read_logs()
	if args.get("cls"):
		from os import system as write
		from platform import platform as pf
		if "Windows" in pf():
			write("cls")
		else:
			write("clear")
	main()
